<?php
namespace app\index\controller;


use app\index\model\Account;
use think\Controller;
use app\index\model\Account as AccountModel;
use app\index\model\User as UserModel;
use app\index\model\Usertree as UTModel;
use app\index\model\Deallist as DLModel;
use app\index\model\Setting as STModel;
use app\index\model\Businesscenter as BCModel;
use think\Session;
use Core;


header("Content-Type: text/html; charset=UTF-8");


//推荐人直推金币增加
//推荐人账户增加 百分之X的金币



class Recommend extends  Base{

    //推荐人设置页面，被直推人可以由当前帐号自由选择放在谁的下层，
    //前提是当前帐号的两个子节点满了的情况下

    public function index(){



        $UserName = Session::get('username');
        $UserID = Session::get('userid');

        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);
//        echo $UserID;

        //初始化User模型
        $User = new UserModel();
        //存放展示的要设置的被推荐人的数组
        $AllRecommendManArr = array();
        //查看当前帐号是否有子推荐人
        $UserStraightChilds = $User->where([
            'pid' => ['EQ',$UserID],
            'pid_status' => ['EQ',1]

        ])->select();

        $ChildrenCount =  count($UserStraightChilds);


        //计算当前账户是否是报单中心账户
        //实例化报单中心表
        $UserBCModel = new BCModel();
        $UserBCModelData = $UserBCModel->where([
            'user_id' => $UserID,
            'status' => 1
        ])->find();

        //有数据，证明是报单中心
        if($UserBCModelData){
            //说明当前用户是生效的报单中心

            //取得当前报单中心级别与佣金百分比
            $BusinessLevel = $UserBCModelData['Business_level'];
            $Business_percent = $UserBCModelData['Business_percent'];

        }

        if($ChildrenCount < 2 || !$UserStraightChilds){
            //当前帐号直接推荐人没有达到2个，或者根本没有 直接推荐人 可以直接设置在当前帐号下
            // echo "小于2个 直接放";

            //取出所有属于本用户的被推荐人ID，没有设置过的！！！
            $AllRecommendManData = $User->where([
                'import_man_id' => ['EQ',$UserID],
                'pid_status' => ['EQ',0]
            ])->order('id')->select();

            if(!$AllRecommendManData){
               $this->error('当前帐号下直接推荐人小于两个！！！如果当前账户第一次进入本页面，请按F5刷新当前页面！');
            }

            //dump($AllRecommendManData);die;
            foreach($AllRecommendManData as $value){
                $AllRecommendManArr[] = $value['id'];
            }
            //dump($AllRecommendManArr);die;

            //设置排在第一个的被推荐人PID为当前用户的ID

            //dump($AllRecommendManData);die;
            $Res = $User->save([

                'pid' => $UserID,
                'pid_status' => 1
            ],[
                'id' => $AllRecommendManArr[0]
            ]);
            //取得推荐人的订单金额
             if(!$Res){
                $this->error("当前账户直接推荐人过少！！！如果当前账户第一次进入本页面，请按F5刷新当前页面！");
            }
            $DealList = new DLModel();
//            $RecommendManPayData = $RecommendManpay->where('')
            $DLRes = $DealList->where([
                'user_id' => ['EQ',$AllRecommendManArr[0]],
                'status' => ['EQ',1]
            ])->order('id')->select();


            if(!$DLRes){
                $this->error("当前账户直接推荐人过少！！！如果当前账户第一次进入本页面，请按F5刷新当前页面！");
            }
//            dump($DLRes);die;


            //得到订单的钱了

            $RecommentManMoney =  $DLRes[0]['deal_price'];

            //更新订单状态
           $UpdateDealListData =  $Deallist->save([

                'tree_status'=> '1'

            ],['id'=>$DLRes[0]['id'],'user_id' => ['EQ',$AllRecommendManArr[0]]]);

           

            //取得比例
            $Setting = new STModel();
            $SettingData = $Setting->find();

            $SellCoin = $SettingData['sell_coin'];

            //计算直推佣金
            $RecommentManCoin = ($RecommentManMoney/100)*$SellCoin;


            //计算报单中心的比例

            $BusinessManMoney = ($RecommentManMoney/100) * $Business_percent;


            //加上直推佣金,得到所有要增加的金币
            $RecommentManCoin = $BusinessManMoney + $RecommentManCoin;




            $Account = new AccountModel();
            //找出原来的总推荐人付款数
            $UserAccount = $Account->where('user_id',$UserID)->find();

//        echo $UserID;
            $UserAccountRecommendManSumPay =  $UserAccount['recommend_man_sum_pay'];
            $UserAccountRecommendManSumPay =  $UserAccountRecommendManSumPay + $RecommentManMoney;


            //原来的金币数
            $UserGoldCoin =  $UserAccount['gold_coin'];
            $RecommentManCoinPlus = $UserGoldCoin + $RecommentManCoin;


           $AccountData =  $Account->save([

                'gold_coin' => $RecommentManCoinPlus,

                'recommend_man_sum_pay' => $UserAccountRecommendManSumPay

            ],[
                'user_id' => $UserID
            ]);

            //更新当前账户的推荐人数
            $CurrentUser = $User->where('id',$UserID)->find();
            $CurrentManCount = $CurrentUser['recommend_man_count'];
            $CurrentManCount = $CurrentManCount + 1;


            //存入当前账户的USER表
            $User->save([

                'recommend_man_count' => $CurrentManCount

            ],[
                'id' => $UserID
            ]);

            //更新推荐订单的状态



            if($Res && $AccountData){

                $this->success("设置成功");
            }else{
                $this->error("设置失败");
            }

        }else if($ChildrenCount >= 2){
            //当前帐号直接推荐人大于2个了,就要看看他的子帐号
            //echo "大于2个 ";
            //直接取出所有import_man_id == $UserID
            $AllRecommendManArr = $User->where('import_man_id',$UserID)->select();
            //说明至少是第一层放完了，查找所有PID等于当前用户ID的人
            $FlushArr =  getChildrensID($AllRecommendManArr,$UserID);
            //压入父ID
            $FlushArr[] = $UserID;


            //找出所有设置过的ID，查看满了的ID
            $AllRecommendManStatusArr = $User->where([
                'import_man_id' => $UserID,
                'pid_status' => 1
            ])->select();

            //dump($AllRecommendManStatusArr);die;
             $AllFullRecommendArr = getFullChildrenID($AllRecommendManStatusArr,$UserID);

            //dump($AllFullRecommendArr);

            //所有的子ID 跟 放满的ID 之差集，就是要得到的差集
            $NoSetRecommendManArr = array_diff($FlushArr,$AllFullRecommendArr);

//            dump($NoSetRecommendManArr);die;

            //返回的数组
            $NoSetRecommendManArrData = array();
            foreach ($NoSetRecommendManArr as $key => $value){

                //去数据库 找出用户名
                $where = array('id' => array('IN',$NoSetRecommendManArr));
                $NoSetRecommendManArrData = $User->where($where)->order('id')->select();
            }

            //dump($NoSetRecommendManArrData);die;

            $this->assign("NoSetArr",$NoSetRecommendManArrData);

            //给出分配数

            $NoSetRecommendManNum = $User->where([
                'import_man_id' => ['EQ',$UserID],
                'pid_status' => ['EQ',0],
                'pid' => ['EQ',0]
            ])->order('id')->select();

            //未设置的人数
            $NoSetNum = count($NoSetRecommendManNum);
            //未设置的人数的数据
            $NoSetInfo = $NoSetRecommendManNum;


            $this->assign('NoSetNum',$NoSetNum);
            $this->assign('NoSetInfo',$NoSetInfo);

            //当前的用户账户金币数
            $Account = new AccountModel;
            $UserAccountInfo = $Account->where('user_id',$UserID)->find();

            $this->assign('UserAccountInfo',$UserAccountInfo);
        }else{
            //错误！！！！
            $this->error('错误！请联系管理员');
        }



        return $this->fetch();
    }

    // //计算区块金额,大小区
    // public function block_Money(){

    //     $UserID = Session::get('userid');


    //      //取得当前审核通过的订单 usertree = 0 status = 1

    //     $Order = new DLModel();


    //     //实例化 节点类
    //     //$BiNode = new \Core\BiNode();
    //     //取得所有设置过的数据
    //     $User  = new UserModel();
    //     $UserData = $User->where([

    //         'pid_status' => ['EQ',1]

    //     ])->select();


    //     //得到整个树
    //     $FlushArr =  getChildrensID($UserData,$UserID);


    //     $OrderData = $Order->where([
    //         'status' => 1,
    //         'usertree' => 0,
    //         'import_man_id' => array('IN',$FlushArr)
    //     ])->select();

    //     $ThisDeal = 0;
    //     $ThisDealID = 0;


    //     if($OrderData){
    //         $ThisDeal = $OrderData[0]['deal_price'];
    //         $ThisDealID = $OrderData[0]['id'];
    //     }else{
    //         $this->error('没有符合的订单!');
    //     }

    //     //取得直接的两个子ID
    //     $UserStraightChildID = $User->where([

    //         'pid_status' => ['EQ',1],
    //         'pid' => $UserID
    //     ])->select();

    //     //存两个直接子节点的数组
    //     $StraightID = array();
    //     foreach ($UserStraightChildID as $v){
    //         $StraightID[] =  $v['id'];
    //     }

    //     $StraightCount = count($StraightID);


    //     //大小区判断开始
    //     if($StraightCount < 2){
    //         //证明直接的子节点没有达到2个,所以不比较大小区
    //         return 0;
    //     }
    //    // echo "tttttttttttttt";
    //     //dump($a);die;



    //     //先算左区
    //     $LeftChildList = getChildrensID($UserData,$StraightID[0]);
    //      //dump($LeftChildList);
    //     //存储左区总付款的变量
    //     $AllLeftMoney = 0;
    //     //实例化订单模型
    //     $DealList = new DLModel();
    //     foreach($LeftChildList as $singlelistV){

    //         $price = $DealList->where([

    //             'status' => ['EQ',1],
    //             'User_id'=> $singlelistV
    //         ])->select();

    //          foreach($price as $singleV){
    //              $AllLeftMoney += $singleV['deal_price'];
    //          }
    //     }

    //     //算右区
    //     $RightChildList = getChildrensID($UserData,$StraightID[1]);

    //     //存储右区总付款的变量
    //     $AllRightMoney = 0;
    //     //实例化订单模型
    //     $DealList = new DLModel();
    //     foreach($RightChildList as $singlelistV){

    //         $price = $DealList->where([

    //             'status' => ['EQ',1],
    //             'User_id'=> $singlelistV
    //         ])->select();

    //         foreach($price as $singleV){
    //             $AllRightMoney += $singleV['deal_price'];
    //         }
    //     }

    //    /* //取得设置中的比例
    //         $SettingModel = new STModel();
    //         $SettingModel->where('')*/

    //         $LowBlockMoney = 0;
    //     //取得小区
    //      if($AllLeftMoney  > $AllRightMoney){
    //          //右区是小区
    //          //当前用户获得订单百分之10的金币，订单金额*10
    //          $LowBlockMoney = ($ThisDeal/100)*10;

    //      }else if($AllLeftMoney  < $AllRightMoney){
    //          //左区是小区
    //          //当前用户获得订单百分之10的金币，订单金额*10
    //          $LowBlockMoney = ($ThisDeal/100)*10;
    //      }

    //      //实例化账户模型
    //      $UserAccount = new Account();
    //      //取得当前账户的金币
    //      $AccountData = $UserAccount->where('userid',$UserID)->find();
    //      $CurrentGoldCoin = $AccountData['gold_coin'];

    //     $NewGoldCoin = $CurrentGoldCoin+$LowBlockMoney;


    //     //把金币存入当前用户账户
    //     $Res = $UserAccount->save([

    //         'gold_coin' => $NewGoldCoin

    //     ],[
    //         'id' => $UserID
    //     ]);

    //     if($Res){
    //         //把当前的订单树状态设置成1
    //         $Order->save([

    //             'tree_status' => 1

    //         ],[
    //             'id' => $ThisDealID
    //         ]);
    //     }else{
    //         $this->error("失败，请联系管理员");
    //     }

    //     //
    // }

    public function hitchRecommend(){

       $UserID = Session::get('userid');
        $HithchInfo = input('post.');


      /*  $HithchInfo['hitchid'] = 24;
        $HithchInfo['sendchildid'] = 26;*/

//       file_put_contents('1.txt',$HithchInfo['hitchid'],FILE_APPEND);
//       file_put_contents('1.txt',$HithchInfo,FILE_APPEND);
//        die;
        $User = new UserModel();
        $Reslut = $User->save([

            'pid' => $HithchInfo['hitchid'],
            'pid_status' => 1

        ],[
            'id' => $HithchInfo['sendchildid']
        ]);

        //推荐人直推金币增加
        //推荐人账户增加 百分之X的金币
        $DealList = new DLModel();

        $DLRes = $DealList->where([
            'user_id' => ['EQ',$HithchInfo['sendchildid']],
            'status' => ['EQ',1]
        ])->order('id DESC')->select();
        /*echo $DLRes[0]['deal_price'];
        dump($DLRes);die;*/
        //得到订单的钱了
        $RecommentManMoney =  $DLRes[0]['deal_price'];

        //取得比例
        $Setting = new STModel();
        $SettingData = $Setting->find();

        $SellCoin = $SettingData['sell_coin'];

        //计算佣金
        $RecommentManCoin = ($RecommentManMoney/100)*$SellCoin;
       //echo $RecommentManCoin;die;

        //计算当前账户是否是报单中心账户
        //实例化报单中心表
        $UserBCModel = new BCModel();
        $UserBCModelData = $UserBCModel->where([
            'user_id' => $UserID,
            'status' => 1
        ])->find();

        //有数据，证明是报单中心
        if($UserBCModelData){
            //说明当前用户是生效的报单中心

            //取得当前报单中心级别与佣金百分比
            $BusinessLevel = $UserBCModelData['Business_level'];
            $Business_percent = $UserBCModelData['Business_percent'];

            //计算报单中心的比例,取得报单中心佣金

            $BusinessManMoney = ($RecommentManMoney/100) * $Business_percent;

            //加上直推佣金
            $RecommentManCoin = $BusinessManMoney + $RecommentManCoin;

        }



        //存入当前用户账户


        $Account = new AccountModel();
        //找出原来的总推荐人付款数
        $UserAccount = $Account->where('user_id',$UserID)->find();

//        echo $UserID;
       $UserAccountRecommendManSumPay =  $UserAccount['recommend_man_sum_pay'];
       $UserAccountRecommendManSumPay =  $UserAccountRecommendManSumPay + $RecommentManMoney;


       //原来的金币数
       $UserGoldCoin =  $UserAccount['gold_coin'];
       $RecommentManCoinPlus = $UserGoldCoin + $RecommentManCoin;


        $Account->save([

            'gold_coin' => $RecommentManCoinPlus,

            'recommend_man_sum_pay' => $UserAccountRecommendManSumPay

        ],[
            'user_id' => $UserID
        ]);

        //更新当前账户的推荐人数
        $CurrentUser = $User->where('id',$UserID)->find();
        $CurrentManCount = $CurrentUser['recommend_man_count'];
        $CurrentManCount = $CurrentManCount + 1;


        //存入当前账户的USER表
         $User->save([

            'recommend_man_count' => $CurrentManCount

        ],[
            'id' => $UserID
        ]);
        //更新订单状态
        $DealList->save([

            'tree_status'=> '1'

        ],[
            'User_id' => $UserID
        ]);





        //  //大小区分成
        // //大小区分成
        // //大小区分成
        // //大小区分成
        // $UserID = Session::get('userid');


        // //实例化 节点类
        // //$BiNode = new \Core\BiNode();
        // //取得所有设置过的数据
        // $User  = new UserModel();
        // $UserData = $User->where([

        //     'pid_status' => ['EQ',1]

        // ])->select();

        // //得到整个树
        // $FlushArr =  getChildrensID($UserData,$UserID);
        // //取得直接的两个子ID
        // $UserStraightChildID = $User->where([

        //     'pid_status' => ['EQ',1],
        //     'pid' => $UserID
        // ])->select();

        // //存两个直接子节点的数组
        // $StraightID = array();
        // foreach ($UserStraightChildID as $v){
        //     $StraightID[] =  $v['id'];
        // }



        // if(count($StraightID) < 2){
        //     //没有2个直接节点，也就是说，下面没有节点
        //     //不算大小区了，直接加入
        //     if($Reslut){
        //         //设置成功
        //         return json_encode($RecommentManCoin);
        //     }else{
        //         //设置失败
        //         return json_encode(0);
        //     }


        // }
        // //先算左区
        // $LeftChildList = getChildrensID($UserData,$StraightID[0]);
        // //dump($LeftChildList);
        // //存储左区总付款的变量
        // $AllLeftMoney = 0;
        // //实例化订单模型
        // $DealList = new DLModel();
        // foreach($LeftChildList as $singlelistV){

        //     $price = $DealList->where([

        //         'status' => ['EQ',1],
        //         'User_id'=> $singlelistV
        //     ])->select();

        //     foreach($price as $singleV){
        //         $AllLeftMoney += $singleV['deal_price'];
        //     }
        // }

        // //算右区
        // $RightChildList = getChildrensID($UserData,$StraightID[1]);

        // //存储右区总付款的变量
        // $AllRightMoney = 0;
        // //实例化订单模型
        // $DealList = new DLModel();
        // foreach($RightChildList as $singlelistV){

        //     $price = $DealList->where([

        //         'status' => ['EQ',1],
        //         'User_id'=> $singlelistV
        //     ])->select();

        //     foreach($price as $singleV){
        //         $AllRightMoney += $singleV['deal_price'];
        //     }
        // }

        // //取得设置中的比例

        // $UserAccount = new AccountModel();
        // //取得小区
        // if($AllLeftMoney  > $AllRightMoney){
        //     //右区是小区
        //      $AllRightMoneyGold = ($AllRightMoney*10)/100;

        //         foreach($RightChildList as $LF){
        //             if($HithchInfo['sendchildid'] == $LF){

        //                 $UserAccount->save([

        //                     'gold_coin' => $AllRightMoneyGold
        //                 ],[
        //                     'id' => $UserID
        //                 ]);
        //             }
        //         }
        // }else{
        //     //左区是小区
        //     $AllLeftMoneyGold = ($AllLeftMoney*10)/100;

        //     foreach($LeftChildList as $RF){

        //         if($HithchInfo['sendchildid'] == $RF){

        //             $UserAccount->save([
        //             'gold_coin' => $AllLeftMoneyGold
        //             ],[
        //                 'id' => $UserID
        //             ]);
        //         }
        //     }
        // }





        // if($Reslut){
        //     //设置成功
        //     return json_encode($RecommentManCoin);
        // }else{
        //     //设置失败
        //     return json_encode(0);
        // }
    }
}
